<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列车时刻表 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand" href="/">
            <img src="/images/logo.jpeg" alt="Logo" class="d-inline-block align-text-top">
            列车车次管理系统
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto">
                <li class="nav-item">
                    <a class="nav-link" href="/">首页</a>
                </li>                <li class="nav-item">
                    <a class="nav-link" href="#" onclick="checkAuthAndRedirect('/user/booking'); return false;">车票预订</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/schedule">时刻表</a>
                </li>
            </ul>
            <ul class="navbar-nav" id="authNav">
                <!-- 动态填充登录状态 -->
            </ul>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-calendar-date me-2"></i>列车时刻表查询</h5>
        </div>
        <div class="card-body">
            <form id="scheduleSearchForm" class="row g-3">
                <div class="col-md-4">
                    <label class="form-label">车次号</label>
                    <input type="text" class="form-control" id="trainNumber" placeholder="例如：G1234">
                </div>
                <div class="col-md-4">
                    <label class="form-label">出发站</label>
                    <select class="form-select" id="startStation">
                        <option value="">-- 选择出发站 --</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">查询日期</label>
                    <input type="date" class="form-control" id="queryDate">
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary me-2">
                        <i class="bi bi-search me-1"></i>查询
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="resetBtn">
                        <i class="bi bi-arrow-clockwise me-1"></i>重置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <h5 class="mb-0" id="resultHeader">
                <i class="bi bi-train-front me-2"></i>时刻表信息
            </h5>
        </div>
        <div class="card-body">
            <div id="loadingSpinner" class="text-center py-5 d-none">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">正在加载时刻表信息...</p>
            </div>

            <div id="noResultMsg" class="alert alert-info d-none">
                <i class="bi bi-info-circle me-2"></i>
                没有找到符合条件的时刻表信息，请调整查询条件后重试。
            </div>

            <div id="scheduleResults" class="d-none">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                        <tr>
                            <th>车次</th>
                            <th>出发站</th>
                            <th>到达站</th>
                            <th>出发时间</th>
                            <th>到达时间</th>
                            <th>运行时长</th>
                            <th>一等座价格</th>
                            <th>二等座价格</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="scheduleTableBody">
                        <!-- 动态加载时刻表数据 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 车次详情模态框 -->
<div class="modal fade" id="scheduleDetailModal" tabindex="-1" aria-labelledby="scheduleDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="scheduleDetailModalLabel">
                    <i class="bi bi-info-circle me-2"></i>车次详细信息
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="scheduleDetailContent">
                <!-- 动态加载详细信息 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="bookFromDetailBtn">立即预订</button>
            </div>
        </div>
    </div>
</div>

<footer class="bg-light text-center text-lg-start mt-5">
    <div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.05);">
        © 2025 列车车次管理系统 -
        <a class="text-dark" href="/">upup.com</a>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="/js/auth.js"></script>
<script>
    let currentScheduleData = null;

    $(document).ready(function() {
        // 检查用户登录状态并更新导航栏
        updateAuthNav();

        // 加载车站数据
        loadStations();

        // 设置默认日期为今天
        const today = new Date();
        $('#queryDate').val(today.toISOString().split('T')[0]);

        // 提交查询表单
        $('#scheduleSearchForm').on('submit', function(e) {
            e.preventDefault();
            searchSchedule();
        });

        // 重置按钮
        $('#resetBtn').on('click', function() {
            $('#scheduleSearchForm')[0].reset();
            $('#queryDate').val(today.toISOString().split('T')[0]);
            $('#scheduleResults').addClass('d-none');
            $('#noResultMsg').addClass('d-none');
        });

        // 查看详情按钮事件
        $('#scheduleTableBody').on('click', '.detail-btn', function() {
            const scheduleId = $(this).data('id');
            showScheduleDetail(scheduleId);
        });

        // 预订按钮事件
        $('#scheduleTableBody').on('click', '.book-btn', function() {
            const scheduleId = $(this).data('id');
            const trainInfo = $(this).data('info');
            redirectToBooking(scheduleId, trainInfo);
        });

        // 从详情页预订
        $('#bookFromDetailBtn').on('click', function() {
            if (currentScheduleData) {
                redirectToBooking(currentScheduleData.id, 
                    `${currentScheduleData.trainNumber} (${currentScheduleData.departureDate} ${currentScheduleData.departureTime})`);
            }
        });
    });

    // 加载车站列表
    function loadStations() {
        $.ajax({
            url: '/api/stations',
            type: 'GET',
            success: function(stations) {
                let options = '<option value="">-- 选择出发站 --</option>';
                stations.forEach(station => {
                    options += `<option value="${station.id}">${station.stationName}</option>`;
                });
                $('#startStation').html(options);
            },
            error: function(err) {
                console.error('无法加载车站数据', err);
            }
        });
    }

    // 查询时刻表
    function searchSchedule() {
        const trainNumber = $('#trainNumber').val().trim();
        const startStationId = $('#startStation').val();
        const queryDate = $('#queryDate').val();

        // 构建查询参数
        let url = '/api/schedules';
        let params = [];

        if (queryDate) {
            params.push(`date=${queryDate}`);
        }

        if (params.length > 0) {
            url += '?' + params.join('&');
        }

        // 显示加载状态
        $('#scheduleResults').addClass('d-none');
        $('#noResultMsg').addClass('d-none');
        $('#loadingSpinner').removeClass('d-none');

        $.ajax({
            url: url,
            type: 'GET',
            success: function(schedules) {
                $('#loadingSpinner').addClass('d-none');

                // 客户端过滤
                let filteredSchedules = schedules;

                if (trainNumber) {
                    filteredSchedules = filteredSchedules.filter(schedule => 
                        schedule.trainNumber && schedule.trainNumber.toLowerCase().includes(trainNumber.toLowerCase())
                    );
                }

                if (startStationId) {
                    filteredSchedules = filteredSchedules.filter(schedule => 
                        schedule.startStationId == startStationId
                    );
                }

                if (filteredSchedules.length === 0) {
                    $('#noResultMsg').removeClass('d-none');
                    return;
                }

                renderScheduleTable(filteredSchedules);
                $('#scheduleResults').removeClass('d-none');
            },
            error: function(err) {
                $('#loadingSpinner').addClass('d-none');
                $('#noResultMsg').removeClass('d-none').html(
                    '<i class="bi bi-exclamation-triangle me-2"></i>查询失败，请稍后重试'
                );
                console.error('查询时刻表失败', err);
            }
        });
    }

    // 渲染时刻表
    function renderScheduleTable(schedules) {
        let tableHtml = '';
        
        schedules.forEach(schedule => {
            const duration = calculateDuration(schedule.departureTime, schedule.arrivalTime);
            const status = getStatusBadge(schedule.status);
            const trainInfo = `${schedule.trainNumber} (${schedule.departureDate} ${schedule.departureTime})`;

            tableHtml += `
                <tr>
                    <td><strong class="text-primary">${schedule.trainNumber || 'N/A'}</strong></td>
                    <td>${schedule.startStationName || 'N/A'}</td>
                    <td>${schedule.endStationName || 'N/A'}</td>
                    <td class="text-primary">${schedule.departureTime || 'N/A'}</td>
                    <td class="text-success">${schedule.arrivalTime || 'N/A'}</td>
                    <td class="text-muted">${duration}</td>
                    <td class="text-info">¥${schedule.firstClassPrice ? schedule.firstClassPrice.toFixed(2) : 'N/A'}</td>
                    <td class="text-warning">¥${schedule.secondClassPrice ? schedule.secondClassPrice.toFixed(2) : 'N/A'}</td>
                    <td>${status}</td>
                    <td>
                        <button class="btn btn-outline-primary btn-sm me-1 detail-btn" 
                                data-id="${schedule.id}" title="查看详情">
                            <i class="bi bi-info-circle"></i>
                        </button>
                        <button class="btn btn-primary btn-sm book-btn" 
                                data-id="${schedule.id}" 
                                data-info="${trainInfo}" title="立即预订">
                            <i class="bi bi-ticket"></i>
                        </button>
                    </td>
                </tr>
            `;
        });

        $('#scheduleTableBody').html(tableHtml);
    }

    // 显示车次详情
    function showScheduleDetail(scheduleId) {
        $.ajax({
            url: `/api/schedules/${scheduleId}`,
            type: 'GET',
            success: function(schedule) {
                currentScheduleData = schedule;
                
                const duration = calculateDuration(schedule.departureTime, schedule.arrivalTime);
                const status = getStatusBadge(schedule.status);

                const detailHtml = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>基本信息</h6>
                            <table class="table table-sm">
                                <tr><td><strong>车次:</strong></td><td>${schedule.trainNumber || 'N/A'}</td></tr>
                                <tr><td><strong>出发站:</strong></td><td>${schedule.startStationName || 'N/A'}</td></tr>
                                <tr><td><strong>到达站:</strong></td><td>${schedule.endStationName || 'N/A'}</td></tr>
                                <tr><td><strong>出发日期:</strong></td><td>${schedule.departureDate || 'N/A'}</td></tr>
                                <tr><td><strong>状态:</strong></td><td>${status}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>时间信息</h6>
                            <table class="table table-sm">
                                <tr><td><strong>出发时间:</strong></td><td class="text-primary">${schedule.departureTime || 'N/A'}</td></tr>
                                <tr><td><strong>到达时间:</strong></td><td class="text-success">${schedule.arrivalTime || 'N/A'}</td></tr>
                                <tr><td><strong>运行时长:</strong></td><td class="text-muted">${duration}</td></tr>
                            </table>
                            
                            <h6 class="mt-3">票价信息</h6>
                            <table class="table table-sm">
                                <tr><td><strong>一等座:</strong></td><td class="text-info">¥${schedule.firstClassPrice ? schedule.firstClassPrice.toFixed(2) : 'N/A'}</td></tr>
                                <tr><td><strong>二等座:</strong></td><td class="text-warning">¥${schedule.secondClassPrice ? schedule.secondClassPrice.toFixed(2) : 'N/A'}</td></tr>
                            </table>
                        </div>
                    </div>
                `;

                $('#scheduleDetailContent').html(detailHtml);
                $('#scheduleDetailModal').modal('show');
            },
            error: function() {
                alert('获取车次详情失败');
            }
        });
    }    // 跳转到预订页面
    function redirectToBooking(scheduleId, trainInfo) {
        // 检查用户登录状态
        $.ajax({
            url: '/api/users/current',
            type: 'GET',
            success: function() {
                window.location.href = `/user/booking?scheduleId=${scheduleId}`;
            },
            error: function() {
                alert('请先登录再预订车票');
                window.location.href = '/custom-login?redirect=' + encodeURIComponent(window.location.href);
            }
        });
    }

    // 计算运行时长
    function calculateDuration(departureTime, arrivalTime) {
        if (!departureTime || !arrivalTime) return 'N/A';
        
        const [depHours, depMinutes] = departureTime.split(':').map(Number);
        let [arrHours, arrMinutes] = arrivalTime.split(':').map(Number);

        // 如果到达时间早于出发时间，表示跨天
        if (arrHours < depHours || (arrHours === depHours && arrMinutes < depMinutes)) {
            arrHours += 24;
        }

        const durationMinutes = (arrHours * 60 + arrMinutes) - (depHours * 60 + depMinutes);
        const hours = Math.floor(durationMinutes / 60);
        const minutes = durationMinutes % 60;

        return `${hours}小时${minutes}分钟`;
    }

    // 获取状态徽章
    function getStatusBadge(status) {
        switch (status) {
            case 'ACTIVE':
                return '<span class="badge bg-success">正常</span>';
            case 'DELAYED':
                return '<span class="badge bg-warning">晚点</span>';
            case 'CANCELLED':
                return '<span class="badge bg-danger">停运</span>';
            default:
                return '<span class="badge bg-secondary">未知</span>';
        }
    }
</script>
</body>
</html>
